<?php
namespace app\api\controller\v1;
use app\admin\controller\Reason;
use app\api\logic\GetAddressLogic;
use app\api\logic\QuanLogic;
use app\api\logic\SendMuLogic;
use app\service\GaodeService;
use app\service\MoneyLogService;
use app\service\OrderService;
use think\Db;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
use app\service\PosterService;
use app\service\TechnService;
use app\admin\logic\ZzLogic;
use app\service\PaymentService;
use think\Log;
use think\Request;


class Lkuse extends Base
{
	public function _initialize()
	{
		parent::_initialize();
	}
    /**
    定时统计在线技师
     */
    public function technician_online(){
        $hover = date('H');
        $technician_list = Db::name('techn')->where('work_status',1)->field('id,nickname,city,county')->select();
        foreach ($technician_list as $key => $value){
            $technician_list[$key]['on_time'] = $hover;
            $technician_list[$key]['techn_id'] = $value['id'];
            $technician_list[$key]['add_time'] = time();
            unset($technician_list[$key]['id']);
        }
        if (!empty($technician_list)){
             Db::name('techn_online')->insertAll($technician_list);
        }
    }

    /**
    定时计算技师在线时长 半小时使用一次
     */
    public function techn_online_add(){
        $techn_list = Db::name('techn')
            ->alias('t')
            ->join('techn_last l','t.id = l.techn_id')
            ->where('t.work_status',1)
            ->field('t.*,l.star_time,l.total_duration')
            ->select();
        foreach ($techn_list as $value){
            if ($value['star_time'] > 0){
                $online_s = time() - $value['star_time'];
                $hover = round($online_s/3600,1);
                if ($hover>0.2){
                    $all_hover = $value['total_duration'] + $hover;
                    Db::name('techn_last')->where('techn_id',$value['id'])->update(['star_time'=>time(),'total_duration'=>$all_hover]);
                    echo $value['nickname']."增加".$hover."小时<br>";
                }

            }else{
                Db::name('techn_last')->where('techn_id',$value['id'])->update(['star_time'=>time()]);
            }
        }

        $not_online = Db::name('techn')
            ->alias('t')
            ->join('techn_last l','t.id = l.techn_id')
            ->where('t.work_status','<>',1)
            ->where('l.star_time','>',0)
            ->where('l.star_time','<',(time()-100))
            ->field('t.*,l.star_time,l.total_duration')
            ->select();
        foreach ($not_online as $values){
            Db::name('techn_last')->where('techn_id',$values['id'])->update(['star_time'=>0]);
        }
    }
    /**
    订单退款, 更改order_id
     */
    public function order_refund(){

        $order_id = 15596;

        $order_info=db::name('order')->where('id',$order_id)->find();

//        if($order_info['status']!=1){
//            exit();
//        }

//		 订单支付方式校验
        $pay_log = Db::name('pay_log')->where(['order_id' => $order_id, 'business_type' => 1])->find();
        if(empty($pay_log))
        {
            echo json_encode(['code' => -100, 'msg' => '支付日志不存在']);
            exit();
        }
        $refund_price = $order_info['pay_price'];

        $pay_status = 2;

        //判断是否为余额支付
        $is_money = false;
        if($pay_log['payment'] == 'MoneyPay')
        {
            //是
            $is_money = true;
        }else
        {
            //否，原路退回
            // 操作退款
            $payment_array = PaymentService::$payment_array;
            $payment = $payment_array[$order_info['payment_id']];
            $pay_name = 'payment\\'.$payment['payment'];
            $pay_params = [
                'order_id'          => $order_info['id'],
                'order_no'          => $order_info['order_no'],
                'trade_no'          => $pay_log['trade_no'],
                'pay_price'         => $order_info['pay_price'],
                'refund_price'      => $refund_price,
                'client_type'       => $order_info['client_type'],
                'refund_reason'     => $order_info['order_no'].'订单退款'.$refund_price.'元',
                'pay_time'          => $order_info['pay_time'],
            ];
            $refund = (new $pay_name($payment['config']['user']))->Refund($pay_params);
        }
        // 退款成功
        if(isset($refund['code']) && $refund['code'] != 0)
        {
            echo json_encode($refund,256);
            exit();
        }

        // 开启事务
        Db::startTrans();
        //退款日志数据
        $refund_log_data = [];
        // 余额退款
        if($is_money === true)
        {
            // 获取用户余额
            $user_info = Db::name('user')->where(['id' => $order_info['user_id']])->find();
            if(empty($user_info))
            {
                Db::rollback();
                echo json_encode(['code' => -100, 'msg' => '用户不存在']);
                exit();
            }
            // 更新余额数据
            $money_data = [
                'money' => Db::raw('money+'.$refund_price),
                'upd_time' => time()
            ];
            if(!Db::name('user')->where(['id' => $user_info['id']])->update($money_data))
            {
                Db::rollback();
                echo json_encode(['code' => -100, 'msg' => '余额操作失败']);
                exit();
            }
            //余额日志
            $money_log_id = Db::name('money_log')->insertGetId([
                'identity_type' => 'user',
                'identity_id' => $user_info['id'],
                'business_type' => 2,
                'money_type' => 0,
                'operation_type' => 1,
                'operation_money' => $refund_price,
                'original_money' => $user_info['money'],
                'latest_money' => $user_info['money']+$refund_price,
                'msg' => '订单超时退款',
                'add_time' => time()
            ]);
            if($money_log_id <= 0)
            {
                Db::rollback();
                echo json_encode(['code' => -100, 'msg' => '余额日志添加失败']);
                exit();
            }
            $refund_log_data = [
                'order_id' => $order_info['id'],
                'trade_no' => '',
                'buyer_user' => '',
                'refund_price' => $refund_price,
                'pay_price' => $order_info['pay_price'],
                'msg' => '订单退款',
                'payment' => $pay_log['payment'],
                'payment_name' => $pay_log['payment_name'],
                'refundment' => 0,
                'business_type' => 1,
                'return_params' => '',
                'add_time' => time(),
                'uid'=>$order_info['user_id'],
                'reason'=>empty($params['reason'])?'超时退款':$params['reason'],
                'day'=>date('Y-m-d')
            ];
        }else
        {
            $refund_log_data = [
                'order_id' => $order_info['id'],
                'trade_no' => isset($refund['data']['trade_no']) ? $refund['data']['trade_no'] : '',
                'buyer_user' => isset($refund['data']['buyer_user']) ? $refund['data']['buyer_user'] : '',
                'refund_price' => isset($refund['data']['refund_price']) ? $refund['data']['refund_price'] : '',
                'pay_price' => $order_info['pay_price'],
                'msg' => '订单退款',
                'payment' => $pay_log['payment'],
                'payment_name' => $pay_log['payment_name'],
                'refundment' => 0,
                'business_type' => 1,
                'return_params' => isset($refund['data']['return_params']) ? json_encode($refund['data']['return_params'], JSON_UNESCAPED_UNICODE) : '',
                'add_time' => time(),
                'uid'=>$order_info['user_id'],
                'reason'=>empty($params['reason'])?'':$params['reason'],
                'day'=>date('Y-m-d')
            ];
        }
        //写入退款日志
        $refund_log_id = Db::name('refund_log')->insertGetId($refund_log_data);
        if($refund_log_id <= 0)
        {
            Db::rollback();
            echo json_encode(['code' => -100, 'msg' => '退款日志添加失败']);
            exit();
        }
        // 更新主订单
        $order_upd_data = [
            'pay_status' => $pay_status,
            'refund_price' => $refund_log_data['refund_price'],
            'status' => 12,//技师不接单
            'close_time' => time(),
            'upd_time' => time(),
            'techn_is_repair'=>1
        ];
        //更新订单状态
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($order_upd_data))
        {
            Db::rollback();
            echo json_encode(['code' => -100, 'msg' => '订单更新失败']);
            exit();
        }
        //添加状态日志
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
            'order_id' => $order_info['id'],
            'original_status' => $order_info['status'],
            'new_status' => $order_upd_data['status'],
            'msg' => '退款['.$status_array[$order_info['status']]['name'].'-'.$status_array[$order_upd_data['status']]['name'].']',
            'identity_type' => 'user',
            'identity_id' => $order_info['user_id'],
            'add_time' => time(),
            'reason'=>empty($params['reason'])?'':$params['reason']
        ]);
        if($order_status_history_id <= 0)
        {
            Db::rollback();
            echo json_encode(['code' => -100, 'msg' => '订单历史状态添加失败']);
            exit();
        }

        //技师未出发结算状态关闭
        $balance_data = [
            'status' => 2,
            'upd_time' => time()
        ];
        if(!Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->update($balance_data))
        {
            Db::rollback();
            echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
            exit();
        }

        //提交事务
        Db::commit();

        //发送模板消息
        //查询技师信息
        $techn_info = Db::name('techn')->where(['id' => $order_info['techn_id']])->find();
        if(!empty($techn_info)) {

            //给用户推送模板消息
            //查询用户的openid
            $user_openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
            if (!empty($user_openid)) {
                $tem_msg = [];
                $tem_msg['touser'] = $user_openid;
                $tem_msg['template_id'] = 'zZ7W-JsnM7OwbWnnuPxodYSCpBrGLOY1X0hKDwFHpT4';
                $tem_msg['url'] = 'https://h5.hexukeji.com/h5/pages/order/orderdetail?order_id=' . $order_info['id'];
                $tem_msg['data'] = [
                    'first' => [
                        'value' => '退款通知',
                        'color' => '#173177'
                    ],
                    'keyword1' => [
                        'value' => $order_info['order_no'],
                        'color' => '#173177'
                    ],
                    'keyword2' => [
                        'value' => $techn_info['nickname'],
                        'color' => '#173177'
                    ],
                    'keyword3' => [
                        'value' => '技师暂无接单',
                        'color' => '#173177'
                    ],
                    'keyword4' => [
                        'value' => $order_info['total_price'] . '元',
                        'color' => '#173177'
                    ],
                    'remark' => [
                        'value' => '退款' . $refund_log_data['refund_price'] . '元，感谢您的使用！',
                        'color' => '#173177'
                    ]
                ];
                UserWeixinService::send_wx_web_tem_msg($tem_msg);
            }
        }
    }

    /**
    太原技师业绩周期计算
     */
    public function techn_yeji(Request $request){
        $param = $request->param();

        $star = strtotime('2023-01-01');
        $end = time();
        if (!empty($param['star'])){
            $star = strtotime($param['star']);
        }
        if (!empty($param['end'])){
            $end = strtotime($param['end']);
        }
        $techn = Db::name('order')->where('shi',140100)->where('status',6)->where('add_time','between',$star.','.$end)->column('techn_id');
        $info = [];
        foreach ($techn as $value){
            $info[$value]['price'] = Db::name('order')->where('status',6)->where('add_time','between',$star.','.$end)->where('techn_id',$value)->sum('price');
        }


        foreach ($info as $k=>$v){
            $info[$k]['name'] = Db::name('techn')->where('id',$k)->value('nickname');
        }

        usort($info, 'cmp');
        for ($i=0;$i<10;$i++){
            $result[$i] = $info[$i];
        }
        dump($result);


    }
    
}